<template>
  <div
    class="d-flex flex-column justify-content-center overflow-hidden page-wrapper"
  >
    <JoinApplicationPhaseStepper />
    <b-form style="margin-top: 19px;">
      <div class="form-segment">
        <p class="form-segment-title">1. 个人信息</p>
        <div class="form-line">
          <label for="username">* 姓名:</label>
          <b-input
            id="username"
            v-model="$v.form.username.$model"
            class="mr-sm-2 mb-sm-0"
            :state="$v.form.username.$dirty ? !$v.form.username.$error : null"
          />
        </div>
        <div class="form-line">
          <label for="idAccount">* 身份证号:</label>
          <b-input
            id="idAccount"
            v-model="$v.form.idAccount.$model"
            class="mr-sm-2 mb-sm-0"
            :state="$v.form.idAccount.$dirty ? !$v.form.idAccount.$error : null"
          />
        </div>
        <div class="form-line-uploader">
          <label for="idPhotoFront">* 手持身份证照:</label>
          <div class="form-line-uploader-group">
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.idPhotoFront"
              :before-upload="beforeUpload.bind(null, 'idPhotoFront')"
              :remove="uploadedImageRemoving"
              :class="{ 'is-invalid': $v.form.idPhotoFront.$error }"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />正面</a-button>
            </a-upload>
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.idPhotoRear"
              :before-upload="beforeUpload.bind(null, 'idPhotoRear')"
              :remove="uploadedImageRemoving"
              :class="{ 'is-invalid': $v.form.idPhotoRear.$error }"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />背面</a-button>
            </a-upload>
          </div>
        </div>
        <div class="form-line">
          <label for="tel">* 联系电话:</label>
          <b-input
            id="tel"
            v-model="$v.form.tel.$model"
            class="mr-sm-2 mb-sm-0"
            :state="$v.form.tel.$dirty ? !$v.form.tel.$error : null"
          />
        </div>
      </div>
      <div class="form-segment" style="margin-top: 19px;">
        <p class="form-segment-title">2. 其他信息</p>
        <div class="form-line-uploader">
          <label for="username">个体工商营业执照:</label>
          <div class="form-line-uploader-group">
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.bizLicense"
              :before-upload="beforeUpload.bind(null, 'bizLicense')"
              :remove="uploadedImageRemoving"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />上传</a-button>
            </a-upload>
            <a-button class="form-line-uploader-group-placeholder">
              <a-icon type="upload" />上传
            </a-button>
          </div>
        </div>
        <div class="form-line">
          <label for="bankAccount">* 银行卡账户:</label>
          <b-input
            id="bankAccount"
            v-model="$v.form.bankAccount.$model"
            class="mr-sm-2 mb-sm-0"
            :state="
              $v.form.bankAccount.$dirty ? !$v.form.bankAccount.$error : null
            "
          />
        </div>
        <div class="form-line">
          <label for="telForBankAccount">* 银行预留手机号:</label>
          <b-input
            id="telForBankAccount"
            v-model="$v.form.telForBankAccount.$model"
            class="mr-sm-2 mb-sm-0"
            :state="
              $v.form.telForBankAccount.$dirty
                ? !$v.form.telForBankAccount.$error
                : null
            "
          />
        </div>
      </div>
      <div class="form-segment" style="margin-top: 19px;">
        <p class="form-segment-title">3. 店铺信息</p>
        <div class="form-line">
          <label for="bizCategory">* 主营类目:</label>
          <b-input
            id="bizCategory"
            v-model="$v.form.bizCategory.$model"
            class="mr-sm-2 mb-sm-0"
            :state="
              $v.form.bizCategory.$dirty ? !$v.form.bizCategory.$error : null
            "
          />
        </div>
        <div class="form-line">
          <label for="managerUsername">店铺管理人姓名:</label>
          <b-input
            id="managerUsername"
            v-model="form.managerUsername"
            class="mr-sm-2 mb-sm-0"
          />
        </div>
        <div class="form-line">
          <label for="managerTel">店铺管理人电话:</label>
          <b-input
            id="managerTel"
            v-model="form.managerTel"
            class="mr-sm-2 mb-sm-0"
          />
        </div>
        <div class="form-line-uploader">
          <label for="idPhotoAdmin">管理人手持身份证照:</label>
          <div class="form-line-uploader-group">
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.idPhotoFrontAdmin"
              :before-upload="beforeUpload.bind(null, 'idPhotoFrontAdmin')"
              :remove="uploadedImageRemoving"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />正面</a-button>
            </a-upload>
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.idPhotoRearAdmin"
              :before-upload="beforeUpload.bind(null, 'idPhotoRearAdmin')"
              :remove="uploadedImageRemoving"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />背面</a-button>
            </a-upload>
          </div>
        </div>
      </div>
      <div class="form-segment" style="margin-top: 19px;">
        <p class="form-segment-title">4. 品牌信息</p>
        <div class="form-line force-inline">
          <label for="trademarkType">品牌商标类型:</label>
          <div class="form-line-radio-group">
            <b-form-radio-group
              v-model="form.trademarkType"
              button-variant="outline-secondary"
              buttons
            >
              <b-form-radio value="0">自有</b-form-radio>
              <b-form-radio value="1">授权</b-form-radio>
            </b-form-radio-group>
          </div>
        </div>
        <div class="form-line">
          <label for="trademarkRegistrationNo">品牌商标注册号:</label>
          <b-input
            id="trademarkRegistrationNo"
            v-model="form.trademarkRegistrationNo"
            class="mr-sm-2 mb-sm-0"
          />
        </div>
        <div class="form-line-uploader">
          <label for="trademarkRegistrationCert">品牌商标注册证明:</label>
          <div class="form-line-uploader-group">
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.trademarkRegistrationCert"
              :before-upload="
                beforeUpload.bind(null, 'trademarkRegistrationCert')
              "
              :remove="uploadedImageRemoving"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />上传</a-button>
            </a-upload>
            <a-button class="form-line-uploader-group-placeholder">
              <a-icon type="upload" />上传
            </a-button>
          </div>
        </div>
        <div class="form-line force-inline">
          <label for="trademarkRegistrationCertValidityPeriod">
            注册证明有效期:
          </label>
          <a-date-picker
            v-model="form.trademarkRegistrationCertValidityPeriod"
            placeholder="请选择"
          />
        </div>
        <div class="form-line-uploader">
          <label for="trademarkAuthorizationCert">品牌商标授权证明:</label>
          <div class="form-line-uploader-group">
            <a-upload
              :name="$options.imageUploadField"
              :action="$options.imageUploadAPI"
              list-type="picture"
              :file-list="uploader.trademarkAuthorizationCert"
              :before-upload="
                beforeUpload.bind(null, 'trademarkAuthorizationCert')
              "
              :remove="uploadedImageRemoving"
              @change="onUploaderStatusChanged"
            >
              <a-button><a-icon type="upload" />上传</a-button>
            </a-upload>
            <a-button class="form-line-uploader-group-placeholder">
              <a-icon type="upload" />上传
            </a-button>
          </div>
        </div>
        <div class="form-line force-inline">
          <label for="trademarkAuthorizationValidityPeriod">
            授权证明有效期:
          </label>
          <!-- <b-input id="idAccount" class="mr-sm-2 mb-sm-0" /> -->
          <a-date-picker
            v-model="form.trademarkAuthorizationValidityPeriod"
            placeholder="请选择"
          />
        </div>
      </div>
      <div class="form-btn">
        <b-button
          variant="outlinesecondary"
          pill
          :disabled="submittingForm"
          @click="onSubmit"
        >
          确认提交
        </b-button>
      </div>
    </b-form>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import { RECORD_SHOP_APPLICATION_AGREEMENT_SOURCE } from '@/assets/constants/mutations/';
import JoinApplicationPhaseStepper from '@/components/m/JoinApplicationPhaseStepper';
import { required } from 'vuelidate/lib/validators';
import siteConfig from '@/assets/config/site';

const UPLOADER_FIELD_ID_NAME_MAPPING = {
  idPhotoFront: '手持身份证照(正面)',
  idPhotoRear: '手持身份证照(背面)',
  bizLicense: '个体工商营业执照',
  idPhotoFrontAdmin: '管理人手持身份证照(正面)',
  idPhotoRearAdmin: '管理人手持身份证照(背面)',
  trademarkRegistrationCert: '品牌商标注册证明',
  trademarkAuthorizationCert: '品牌商标授权证明',
};

export default {
  imageUploadAPI: `${siteConfig.apiPrefix}${siteConfig.assetsUploadAPI}`,
  imageUploadField: siteConfig.assetsUploadField,
  individualJoinApplicationAPI: `${siteConfig.apiPrefix}${siteConfig.individualJoinApplicationAPI}`,
  components: {
    JoinApplicationPhaseStepper,
  },
  layout: 'staticBanner',
  head() {
    return {
      title: '个人/个体户入驻申请',
    };
  },
  data() {
    return {
      submittingForm: false,
      form: {
        username: null,
        idAccount: null,
        idPhotoFront: null,
        idPhotoRear: null,
        tel: null,
        bankAccount: null,
        telForBankAccount: null,
        bizCategory: null,
        managerUsername: null,
        managerTel: null,
        bizLicense: null,
        idPhotoFrontAdmin: null,
        idPhotoRearAdmin: null,
        trademarkType: 0,
        trademarkRegistrationNo: null,
        trademarkRegistrationCert: null,
        trademarkRegistrationCertValidityPeriod: null,
        trademarkAuthorizationCert: null,
        trademarkAuthorizationValidityPeriod: null,
      },
      uploader: {
        idPhotoFront: [],
        idPhotoRear: [],
        bizLicense: [],
        idPhotoFrontAdmin: [],
        idPhotoRearAdmin: [],
        trademarkRegistrationCert: [],
        trademarkAuthorizationCert: [],
      },
    };
  },
  computed: {
    ...mapState(['shopApplicationAgreementAccepted']),
  },
  mounted() {
    if (!this.shopApplicationAgreementAccepted) {
      this.recordAgreementSource('individual');
      this.$router.replace('/agreement');
    }
  },
  methods: {
    async onSubmit() {
      this.$v.$touch();
      if (this.$v.$invalid) {
        this.$message.error('请填入必填项');
        return;
      }

      this.submittingForm = true;
      try {
        await this.$axios.$post(
          this.$options.individualJoinApplicationAPI,
          this.form
        );
        this.resetForm();
        this.submittingForm = false;
        this.$router.replace('/application/submitted');
      } catch (err) {
        this.submittingForm = false;
        if (err.response && err.response.data && err.response.data.msg) {
          this.$message.error(err.response.data.msg);
        } else {
          this.$message.error('网络错误，请稍后再试');
        }
      }
    },
    resetForm() {
      this.$v.$reset();
      this.form = {
        username: null,
        idAccount: null,
        idPhotoFront: null,
        idPhotoRear: null,
        tel: null,
        bankAccount: null,
        telForBankAccount: null,
        bizCategory: null,
        managerUsername: null,
        managerTel: null,
        bizLicense: null,
        idPhotoFrontAdmin: null,
        idPhotoRearAdmin: null,
        trademarkType: 0,
        trademarkRegistrationNo: null,
        trademarkRegistrationCert: null,
        trademarkRegistrationCertValidityPeriod: null,
        trademarkAuthorizationCert: null,
        trademarkAuthorizationValidityPeriod: null,
      };
      this.uploader = {
        idPhotoFront: [],
        idPhotoRear: [],
        bizLicense: [],
        idPhotoFrontAdmin: [],
        idPhotoRearAdmin: [],
        trademarkRegistrationCert: [],
        trademarkAuthorizationCert: [],
      };
    },
    beforeUpload(targetField, file) {
      file.targetField = targetField;
      return true;
    },
    uploadedImageRemoving(file) {
      const targetField = file.targetField;
      this.form[targetField] = null;
      if (this.$v.form[targetField]) {
        this.$v.form[targetField].$touch();
      }
      return true;
    },
    onUploaderStatusChanged(info) {
      const { file, fileList } = info;
      const targetField = file.targetField;
      const targetName = UPLOADER_FIELD_ID_NAME_MAPPING[targetField] || '图片';
      if (file.status === 'error') {
        this.$message.error(`上传${targetName}失败，请稍后再试`);
        this.uploader[targetField] = fileList.slice(0, -1);
        return;
      }
      if (file.status === 'done') {
        let imgPath = null;
        try {
          imgPath = file.response.data.url;
        } catch {
          imgPath = null;
        }
        if (!imgPath) {
          this.$message.error(`上传${targetName}失败，请稍后再试`);
          return;
        }
        this.$message.success(`上传${targetName}成功`);
        this.form[targetField] = imgPath;
        if (this.$v.form[targetField]) {
          this.$v.form[targetField].$touch();
        }
      }
      this.uploader[targetField] = fileList.slice(-1);
    },
    ...mapMutations({
      recordAgreementSource: RECORD_SHOP_APPLICATION_AGREEMENT_SOURCE,
    }),
  },
  validations: {
    form: {
      username: {
        required,
      },
      idAccount: {
        required,
      },
      idPhotoFront: {
        required,
      },
      idPhotoRear: {
        required,
      },
      tel: {
        required,
      },
      bankAccount: {
        required,
      },
      telForBankAccount: {
        required,
      },
      bizCategory: {
        required,
      },
    },
  },
};
</script>

<style lang="scss" scoped>
$inline-control-padding-left: 24px;
$inline-control-padding-right: 12px;

.page-wrapper {
  height: 100%;
  background-color: #f3f3f3;
  @include media-breakpoint-up(sm) {
    padding-top: $main-nav-bar-height;
  }
}
form {
  font-size: 13px;
  line-height: 18px;
  letter-spacing: 0.27px;
  text-align: right;
  max-width: 420px;
  width: 100%;
  align-self: center;
  @include media-breakpoint-down(xs) {
    padding-left: 24px;
    padding-right: 24px;
  }
}
.form-line {
  width: 100%;
  font-family: 'PingFangSC-Regular', 'PingFang SC';
  font-size: 13px;
  line-height: 20px;
  color: #4a4a4a;
  letter-spacing: 0.27px;
  display: flex;
  @include media-breakpoint-down(xs) {
    height: 36px;
    align-items: center;
    label {
      flex: 0 0 124px;
      margin-bottom: 0px;
      text-align: right;
    }
    input {
      flex: 1 1 auto;
      border-color: transparent;
      font-family: 'PingFangSC-Regular', 'PingFang SC';
      font-size: 13px;
      line-height: 18px;
      letter-spacing: 0.27px;
      margin-left: 0.5rem;
      padding-left: 0.5rem;
      background-color: #f3f3f3;
    }
    input.is-invalid {
      border-color: #dc3545;
      box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
    }
  }
  @include media-breakpoint-up(sm) {
    flex-direction: column;
    align-items: flex-start;
    margin: 0.5rem 0px 1.5rem 24px;
    text-align: left;
    &.force-inline {
      flex-direction: row;
      align-items: center;
      label {
        flex: 0 0 124px;
        margin-bottom: 0px;
      }
    }
  }
  .ant-calendar-picker {
    width: 100%;
    margin-left: $inline-control-padding-left;
  }
  ::v-deep .ant-calendar-picker-input {
    font-family: 'PingFangSC-Regular', 'PingFang SC';
    font-size: 13px;
    line-height: 18px;
    letter-spacing: 0.27px;
  }
}
.form-line-uploader {
  width: 100%;
  min-height: 36px;
  display: flex;
  align-items: flex-start;
  font-family: 'PingFangSC-Regular', 'PingFang SC';
  font-size: 13px;
  line-height: 20px;
  color: #4a4a4a;
  letter-spacing: 0.27px;
  @include media-breakpoint-down(xs) {
    text-align: right;
  }
  @include media-breakpoint-up(sm) {
    text-align: left;
    margin-left: 24px;
    margin: 0.5rem 0px 1.5rem 24px;
  }
  label {
    flex: 0 0 124px;
    margin-bottom: 0px;
    line-height: 36px;
  }
  // input {
  //   flex: 1 1 auto;
  //   border-color: transparent;
  // }
}
.form-line-uploader-group {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-left: $inline-control-padding-left;
  padding-right: $inline-control-padding-right;
  ::v-deep .ant-upload-select-picture {
    width: 100%;
    text-align: center;
    line-height: 36px;
  }
  ::v-deep .is-invalid {
    .ant-btn {
      border-color: #dc3545;
    }
  }
  ::v-deep .ant-upload-btn {
    line-height: 36px;
    font-size: 13px;
    letter-spacing: 0.27px;
    .ant-btn {
      height: 32px;
      line-height: 30px;
      font-size: 13px;
      letter-spacing: 0.27px;
      padding: 0 12px;
    }
    i.anticon {
      vertical-align: baseline;
    }
  }
  ::v-deep .ant-upload-list-item {
    margin-top: 0px;
    margin-bottom: 8px;
    .anticon-close {
      font-size: 14px;
      top: 2px;
      right: 2px;
    }
  }
  ::v-deep .ant-upload-list-item-name {
    display: none;
  }
  ::v-deep .ant-upload-list-item-thumbnail {
    position: static;
  }
}
.form-line-uploader-group-placeholder {
  visibility: hidden;
}
.form-line-radio-group {
  width: 100%;
  .btn-group {
    display: flex;
    justify-content: space-between;
    padding-left: $inline-control-padding-left;
    padding-right: $inline-control-padding-right;
  }
  label {
    line-height: 30px;
    font-size: 13px;
    letter-spacing: 0.27px;
    display: inline-block;
    flex: unset !important;
    padding: 0 12px;
    border-top-right-radius: 4px !important;
    border-bottom-right-radius: 4px !important;
    border-top-left-radius: 4px !important;
    border-bottom-left-radius: 4px !important;
    border: 1px solid rgb(217, 217, 217);
    border-radius: 4px;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);
  }
}
.form-segment {
  width: 100%;
  // @include make-col-ready();
  // padding-left: 29px;
  // @include media-breakpoint-up(sm) {
  //   padding-left: 0px;
  //   width: percentage(8 / 12);
  // }
  // @include media-breakpoint-up(md) {
  //   width: percentage(6 / 12);
  // }
  // @include media-breakpoint-up(lg) {
  //   width: percentage(4 / 12);
  // }
}
.form-segment-title {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  line-height: 20px;
  letter-spacing: 0.29px;
  margin: 0px;
  text-align: left;
}
.form-btn {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    max-width: 420px;
    width: 100%;
    height: 50px;
    font-size: 14px;
    color: #4a4a4a;
    line-height: 20px;
    letter-spacing: 0.5px;
    background: #fff;
    box-shadow: 0 1px 8px -2px rgba(0, 0, 0, 0.5);
    margin: 30px 30px 20px;
  }
}
</style>
